/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo.ui.snap;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

/**
 * Created with IntelliJ IDEA.
 * User: vacoor
 * Date: 13-8-19
 * Time: 上午12:09
 * To change this template use File | Settings | File Templates.
 */
public class SnapCanvansListener extends MouseAdapter {
    private BufferedImage backgroundImage;
    private Canvas canvas;
    private Dialog dialog;
    private int x;
    private int y;

    public SnapCanvansListener(BufferedImage bgi, Canvas canvas, Dialog dialog) {
        this.backgroundImage = bgi;
        this.canvas = canvas;
        this.dialog = dialog;

    }

    @Override
    public void mousePressed(MouseEvent e) {
        this.x = e.getX();
        this.y = e.getY();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        Point eP = e.getLocationOnScreen();

        if (e.getX() == this.x && e.getY() == this.y) {
            return;
        }
        Point cP = canvas.getLocationOnScreen();
        Dimension size = dialog.getSize();

        dialog.setLocation(new Point(eP.x - size.width, eP.y + 5));
        dialog.setVisible(true);

        this.x = e.getX();
        this.y = e.getY();
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        int width = e.getX() - x;
        int height = e.getY() - y;
        Graphics2D g2d = (Graphics2D) canvas.getGraphics();
        Stroke oldStroke = g2d.getStroke();
        Color oldColor = g2d.getColor();

        Stroke dash = new BasicStroke(
                2f,   //宽度
                BasicStroke.CAP_ROUND,
                BasicStroke.JOIN_ROUND,
                3.5f,
                new float[]{7f, 7f},   // 间隔
                5f);
        g2d.setStroke(dash);
        g2d.setColor(new Color(0.8f, 0.8f, 0.8f, 0.8f));
        g2d.clearRect(x, y, backgroundImage.getWidth(), backgroundImage.getHeight());
        g2d.drawImage(backgroundImage, 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight(), null);
        g2d.drawRoundRect(x, y, width, height, 5, 5);

        //
        g2d.setStroke(oldStroke);
        g2d.setColor(oldColor);
    }
}
